"""获取所有剧名类"""
import json
import requests
import redis
from lxml import etree

redis_client = redis.StrictRedis()  # 创建redis数据库连接


def bilibili_home():
    """获取哔哩哔哩首页视频分类索引"""
    url = 'https://www.bilibili.com/'  # 请求地址
    header = {
        
    } # 请求头配置
    try:
        response = requests.get(url, headers=header)  # 请求网址
    except Exception as e:
        print(e)
    html = response.content.decode('utf-8')  # 获取网页源码
    root = etree.HTML(html)  # 解析网页
    # 获取剧名分类列表
    video_type = root.xpath('')
    # 获取剧名地址列表
    video_url = root.xpath('')
    # 获取视频完整网址
    video_url = ['https:' + x for x in video_url]
    video_title = list(map(lambda x: {'title': x}, video_type))  # 将类型映射成键值格式
    for i in range(len(video_url)):
        # 将连接加到对应的剧类中
        video_title[i]['href'] = video_url[i]
    with open("../json/bilibili_home.json", 'a', encoding='gbk') as f:
        # 将数据整体加入到json文件中
        f.write(json.dumps(video_title, ensure_ascii=False,indent=4))
    for video in video_title:
        # 遍历列表 将每条数据加入redis数据据库中！方便后续使用多线程
        result = json.dumps(video, ensure_ascii=False)
        print(result)  #打印当前信息
        redis_client.rpush('bilibili_home', result)  # 推入数据库中


# if __name__ == '__main__':
#     bilibili_home()
